//package com.hu.manage.shiro;
//
//import com.google.gson.Gson;
//import com.google.gson.GsonBuilder;
//import com.hu.common.MyResponseBody;
//import org.apache.shiro.authc.AuthenticationToken;
//import org.apache.shiro.web.filter.AccessControlFilter;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.http.HttpHeaders;
//import org.springframework.stereotype.Component;
//
//import javax.servlet.ServletRequest;
//import javax.servlet.ServletResponse;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.util.Objects;
//
//@Component
//public class StatelessAuthFilter extends AccessControlFilter {
//
//    private static final Logger logger = LoggerFactory.getLogger(StatelessAuthFilter.class.getSimpleName());
//
//    @Override
//    protected boolean isAccessAllowed(ServletRequest request,
//                                      ServletResponse response, Object mappedValue) throws Exception {
//        String token = getToken((HttpServletRequest) request);
//        try {
//            AuthenticationToken statelessToken = new StatelessToken(token);
//            getSubject(request, response).login(statelessToken);
//        } catch (Exception e) {
//            logger.error(e.getLocalizedMessage());
//            return false;
//        }
//        return true;
//    }
//
//    @Override
//    protected boolean onAccessDenied(ServletRequest request,
//                                     ServletResponse response) throws Exception {
//        Gson gson = new GsonBuilder().serializeNulls().create();
//        HttpServletResponse resp = (HttpServletResponse) response;
//        resp.setHeader(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8");
//        resp.getWriter().write(gson.toJson(MyResponseBody.unauthorizedError("身份认证失败")));
//        return false;
//    }
//
//    private String getToken(HttpServletRequest request) {
//        String token = request.getHeader(HttpHeaders.AUTHORIZATION);
//        if (Objects.nonNull(token)) {
//            String[] authorizations = token.split(" ");
//            if (!"Bearer".equals(authorizations[0])) {
//                return "";
//            }
//            if (!"".equals(authorizations[1])) {
//                return authorizations[1];
//            }
//        }
//        return "";
//    }
//}
